package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DAO.RoleDAO;
import hibernate.Role;
import java.util.List;
import java.util.Vector;

/**
 * Servlet implementation class InfoJSServlet
 */
public class InfoJSServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InfoJSServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter pw = response.getWriter();
		String un = request.getParameter("un");
		int userID = Integer.parseInt(request.getParameter("userID"));
		RoleDAO role = new RoleDAO();
		Vector v = new Vector();
		Vector v_all = new Vector();
		int num=0;
		String string = "{result:[";
		if(un.equalsIgnoreCase("-1")){
			v = role.getrolename();
			List list = (List)v.elementAt(0);
			for(int i=0;i<list.size();i++){
				int id = ((Role)list.get(i)).getRoleID();
				string = string + "{value:"+id+",text:'"+id +"."+((Role)list.get(i)).getName()+"'}";
				if(i!=list.size()-1)
					string += ",";
			}
		}else{
			v = role.select(userID);
			v_all = role.getAll("0", "-1");
			List l = (List)v_all.get(1);
			if(un.equalsIgnoreCase("0")){
				for(int i=0;i<v.size();i+=2){
					int id = (Integer)v.get(i);
					string = string + "{value:"+id+",text:'"+id +"."+(String)v.get(i+1)+"'}";
					if(i!=v.size()-2)
						string += ",";
				}
			}else if(un.equalsIgnoreCase("1")){
				for(int i=0;i<l.size();i++){
					int id = ((Role)l.get(i)).getRoleID();
					for(int j=0;j<v.size();j+=2){
						if(id == (Integer)v.get(j)){
							num = 1;
						}
					}
					if(num == 0){
						string = string + "{value:"+id+",text:'"+id +"."+((Role)l.get(i)).getName()+"'}";
						if(i!=l.size()-1)
							string += ",";
					}
					num = 0;
				}
			}
		}
		string = string +"]}";
		pw.println(string);
		pw.flush();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
